package cn.com.cetccst.location;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.fence.GeoFence;
import com.amap.api.location.AMapLocation;

import java.util.Locale;

public class GenFenceBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (context == null) {
            Log.i(GeoFenceManager.TAG, "can not handle action for null context");
            return;
        }
        Log.i(GeoFenceManager.TAG, "got action: " + intent.getAction());
        if (GeoFenceManager.GEOFENCE_BROADCAST_ACTION.equals(intent.getAction())) {
            //获取Bundle
            Bundle bundle = intent.getExtras();
            //获取围栏行为：
            int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
            //获取自定义的围栏标识：
            String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
            //获取围栏ID:
            String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
            //获取当前有触发的围栏对象：
            GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
            if (fence != null) {
                AMapLocation currentLocation = fence.getCurrentLocation();
                LocationService.getInstance().cacheLocation(currentLocation);
                Log.i(GeoFenceManager.TAG, String.format(Locale.ENGLISH, "received amap geo fence current location, address:[%s]", currentLocation.getAddress()));

                Log.i(GeoFenceManager.TAG, String.format(Locale.ENGLISH, "received amap geo fence action, status:[%d], customId:[%s], fenceId:[%s], center:[%f,%f]", status, customId, fenceId, fence.getCenter().getLatitude(), fence.getCenter().getLongitude()));
            } else {
                Log.e(GeoFenceManager.TAG, String.format(Locale.ENGLISH, "received amap geo fence action, status:[%d], customId:[%s], fenceId:[%s], center:[-,-]", status, customId, fenceId));

            }
            if (status == GeoFence.STATUS_IN || status == GeoFence.STATUS_OUT || status == GeoFence.STATUS_UNKNOWN) {
                LocationService.getInstance().getGeoFenceManager().updateStatus(fenceId, status);
            }
        }
    }
}
